package com.hll.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author: Mr.Hu
 * @create: 2021-03-09 17:42
 */
public class MybatisUtil {
  // 应该保持一个factory实例存在,相当于 session的连接池
  private static SqlSessionFactory sqlSessionFactory = null;

  static {
    try {
      String resource = "mybatis-config.xml";
      InputStream inputStream = Resources.getResourceAsStream(resource);
      sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); // Builder用完即没用了
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  public static SqlSession getSqlSession() {
    /*true事务自动提交*/
    /* return sqlSessionFactory.openSession(true);*/
    return sqlSessionFactory.openSession(); // 线程不安全，所以一次请求用完即关
  }
}
